<template>
  <div class="alarm-settings">
    <div class="config-select">
      <span>设置名称</span>
      <el-select
        v-model="selectedConfig"
        placeholder="选择配置"
        style="width: 200px"
        @change="handleConfigChange"
      >
        <el-option
          v-for="item in configOptions"
          :key="item.id"
          :label="item.fullname"
          :value="item.id"
        />
      </el-select>
      <el-button @click="editConfig" :disabled="!isEditConfig">编辑配置</el-button>
      <el-button @click="useConfig" :disabled="!editing">使用配置</el-button>
      <el-button @click="addConfig">新增配置</el-button>
    </div>

    <el-form
      :model="form"
      label-position="left"
      :rules="rules"
      ref="formRef"
      class="settings-form"
    >
      <div class="form-row">
        <div class="form-item">
          <el-form-item label="配置名称：" prop="name">
            <el-input v-model="form.name" :disabled="editing" />
          </el-form-item>
        </div>
        <div class="form-item">
          <el-form-item label="基准导高：" prop="ydefault">
            <el-input v-model="form.ydefault" :disabled="editing" style="min-width: 160px;">
              <template #suffix>
                <span>（mm）</span>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <div class="form-item">
          <el-form-item label="适用类型：" prop="type">
            <el-select v-model="form.type" placeholder="选择类型" :disabled="editing" style="width: 150px">
              <el-option
                v-for="item in lineTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
      </div>

      <el-form-item label="导高偏离基准预警值：" prop="ywarn">
        <el-input v-model="form.ywarn" :disabled="editing" style="width: 150px;">
          <template #prefix>±</template>
          <template #suffix>
            <span>（mm）</span>
          </template>
        </el-input>
        <span class="range-hint">
          导高预警范围：{{ yWarnRange }}
        </span>
      </el-form-item>

      <el-form-item label="导高偏离基准超限值：" prop="ypolice">
        <el-input v-model="form.ypolice" :disabled="editing" style="width: 150px;">
          <template #prefix>±</template>
          <template #suffix>
            <span>（mm）</span>
          </template>
        </el-input>
        <span class="range-hint">
          导高超限范围：{{ yPoliceRange }}
        </span>
      </el-form-item>

      <el-form-item label="拉出值预警边界：" prop="xwarn">
        <el-input v-model="form.xwarn" :disabled="editing" style="width: 150px;">
          <template #prefix>±</template>
          <template #suffix>
            <span>（mm）</span>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="拉出值超限边界：" prop="xpolice">
        <el-input v-model="form.xpolice" :disabled="editing" style="width: 150px;">
          <template #prefix>±</template>
          <template #suffix>
            <span>（mm）</span>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <div class="form-actions">
      <el-button @click="handleSubmit(formRef)" type="primary">确认</el-button>
      <el-button @click="handleReset(formRef)">重置</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { GetConfigList, AddLineConfig, EditLineConfig, UseLineConfig } from '@/api/api'
import { echartsParamsManager } from '@/storage/EchartsPrograms'

const emit = defineEmits<{
  settingsChange: [settings: any]
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive({
  name: '',
  type: '',
  ydefault: '',
  ywarn: '',
  ypolice: '',
  xwarn: '',
  xpolice: ''
})

// 配置选项
const configOptions = ref<any[]>([])
const selectedConfig = ref(0)
const isEditConfig = ref(true)
const editing = ref(true)

// 线路类型选项
const lineTypeOptions = [
  { value: '1', label: '区间' },
  { value: '2', label: '站区' },
  { value: '3', label: '隧道' }
]

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 2, max: 30, message: '2到30个字符', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择适用类型', trigger: 'change' }],
  ydefault: [{ required: true, message: '请输入导高基准值', trigger: 'blur' }],
  ywarn: [{ required: true, message: '请输入导高偏离基准预警值', trigger: 'blur' }],
  ypolice: [{ required: true, message: '请输入导高偏离基准超限值', trigger: 'blur' }],
  xwarn: [{ required: true, message: '请输入拉出值预警值', trigger: 'blur' }],
  xpolice: [{ required: true, message: '请输入拉出值超限值', trigger: 'blur' }]
})

// 计算属性
const yWarnRange = computed(() => {
  const ydefault = Number(form.ydefault) || 0
  const ywarn = Number(form.ywarn) || 0
  return `${ydefault - ywarn} ~ ${ydefault + ywarn}`
})

const yPoliceRange = computed(() => {
  const ydefault = Number(form.ydefault) || 0
  const ypolice = Number(form.ypolice) || 0
  return `${ydefault - ypolice} ~ ${ydefault + ypolice}`
})

// 事件处理
const handleConfigChange = () => {
  resetForm(formRef.value)
  editing.value = true
  isEditConfig.value = true

  const config = configOptions.value.find(p => p.id === selectedConfig.value)
  if (config) {
    Object.assign(form, {
      name: config.name,
      type: config.type,
      ydefault: config.ydefault,
      ywarn: config.ywarn,
      ypolice: config.ypolice,
      xwarn: config.xwarn,
      xpolice: config.xpolice
    })
  }
}

const editConfig = () => {
  editing.value = false
  isEditConfig.value = true
}

const addConfig = () => {
  isEditConfig.value = false
  editing.value = false
  Object.assign(form, {
    name: '',
    type: '',
    ydefault: '',
    ywarn: '',
    ypolice: '',
    xwarn: '',
    xpolice: ''
  })
  resetForm(formRef.value)
}

const useConfig = () => {
  // 更新参数管理器
  echartsParamsManager.updateState('xdefault', Number(form.xwarn) || echartsParamsManager.xdefault.value)
  echartsParamsManager.updateState('ydefault', Number(form.ydefault) || echartsParamsManager.ydefault.value)
  echartsParamsManager.updateState('xpolice', Number(form.xpolice) || echartsParamsManager.xpolice.value)
  echartsParamsManager.updateState('yvariable', Number(form.ywarn) || echartsParamsManager.yvariable.value)
  echartsParamsManager.updateState('ypolice', Number(form.ypolice) || echartsParamsManager.ypolice.value)

  const params = {
    ydefault: echartsParamsManager.ydefault.value,
    xwrarn: echartsParamsManager.xdefault.value,
    ywarn: echartsParamsManager.yvariable.value,
    ypolice: echartsParamsManager.ypolice.value,
    xpolice: echartsParamsManager.xpolice.value
  }

  UseLineConfig(params).then(() => {
    console.log('使用配置成功')
    emit('settingsChange', params)
  }).catch(err => {
    console.error('使用配置失败:', err)
  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {
    if (valid) {
      submitSettings()
    } else {
      console.log('表单验证失败:', fields)
    }
  })
}

const handleReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const submitSettings = () => {
  const params = {
    Name: form.name,
    Type: form.type,
    Ydefault: Number(form.ydefault),
    Ywarn: Number(form.ywarn),
    Ypolice: Number(form.ypolice),
    Xwarn: Number(form.xwarn),
    Xpolice: Number(form.xpolice)
  }

  if (isEditConfig.value) {
    const editParams = { ...params, Id: selectedConfig.value }
    EditLineConfig(editParams).then(() => {
      loadConfigList()
      emit('settingsChange', params)
    }).catch(err => {
      console.error('编辑配置失败:', err)
    })
  } else {
    AddLineConfig(params).then(() => {
      loadConfigList()
      emit('settingsChange', params)
    }).catch(err => {
      console.error('新增配置失败:', err)
    })
  }
}

const loadConfigList = () => {
  GetConfigList().then(res => {
    configOptions.value = res.data || []
  }).catch(err => {
    console.error('获取配置列表失败:', err)
  })
}

// 初始化
const init = () => {
  loadConfigList()
}

// 调用初始化
init()
</script>

<style scoped>
.alarm-settings {
  padding: 20px;
}

.config-select {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 30px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

.settings-form {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.form-item {
  flex: 1;
  min-width: 200px;
}

.range-hint {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}

.form-actions {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.form-actions .el-button {
  margin: 0 10px;
  min-width: 100px;
}
</style>